import axios from 'axios'
import store from '@/store'
import router from '@/router'
import {getTimeStamp} from '@/utils/auth'

import { Message } from 'element-ui'

const TimeOut = 3600

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

const isCheckTime = function() {
  const start = getTimeStamp(),
    end = Date.now(),
    res = (end - start) / 1000

  return res > TimeOut ? true : false
}

service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['Authorization'] = `Bearer ${store.getters.token}`

    // 有token发请求代表登录成功，这个时候才有必要检查时间戳是否过期， 所以需要放到 检查token存在成功后
    var flag = isCheckTime()

    if(flag) {
      // 超时了， 结束吧，别发请求了，退出页面，重新登陆吧
      store.commit('test/removeToken')
      store.commit('test/reomveUserInfo')
      router.push('/login')
      Message.error('登录超时,请重新登录')
      return Promise.reject(new Error('token超时了'))
    }
  }
  return config
}, error => {
  return Promise.reject(error)
})

service.interceptors.response.use(response => {
  const { success, message, data } = response.data
  if (success) {
    return data
  } else {
    Message.error(message)
    return Promise.reject(new Error(message))
  }
}, error => {
  if (error.response && error.response.data && error.response.data.code === 10002) {
    store.commit('test/removeToken')
    store.commit('test/reomveUserInfo')

    router.push('/login')
  } else {
    Message.error(error.message)
  }
  return Promise.reject(error)
})

export default service
